import { reactive } from 'vue';

import Map from '/@/utils/rw/map';
import { useMessage } from '/@/hooks/web/useMessage';
import { defHttp } from '/@/utils/http/axios';
import { getToken } from '/@/utils/auth';
import Sub from './sub';

const { createMessage: msg } = useMessage();
// import { mapStore } from '/@/store/modules/map'
// const mapData = mapStore()

const positionTime: number = 2000;
window.wsObjTimer = null;
enum API {
  mapInfo = 'Maps/Detailed',
  realPosition = 'locations/GetRealtime',
}
interface IMapOptions {
  el: string;
  mapListApi?: string;
  mapId?: string;
}

export const useMap = (options: IMapOptions) => {
  let map = reactive<any>(null);
  const windowInstance: any = window;
  const token: string = getToken();
  let posIndex = 0;
  map = new Map(options.el, options);
  if (options.mapId) {
    loadMap({ id: options.mapId });
  }

  function loadMap(obj) {
    return new Promise((resolve, reject) => {
      map
        .loadMap({
          imageFullUrl: `${windowInstance.config.base_url}Maps/pic/${obj.id}?access_token=${token}`,
          width: 50,
          height: 50,
          code: obj.code,
          id: obj.id,
        })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          msg.error('地图文件加载失败');
          reject(err);
        });
    });
  }

  function initPosition(params, cb, asd) {
    window.wsObjTimer = setInterval(async () => {
      // async () => {
      let res;
      if (params.search) {
        delete params.MapId;
        res = await defHttp.post({
          url: API.realPosition,
          data: params,
        });
        if (res.data.length) {
          const mapCode = res.data[0].mapCode;
          // let oldMapCode = map.mapObj.code
          // if (mapCode != oldMapCode) {
          Sub.$trigger('toogleMap', { key: '', item: { code: mapCode }, tagCode: params.TeId });
          // }
        }
        cb && cb();
      } else {
        res = await defHttp.post({ url: API.realPosition, data: params });
        typeof cb === 'function' && cb();
      }

      //将获取的实时数据进行收起
      // mapData.setRealMapData(res.data)
      /*
        removeLayerFlag 当数据定位需要第一次重新检索的时候，将上次的检索数据为空
      */
      if (res.data.length === 0 || params.removeLayerFlag) {
        params.removeLayerFlag = false;
        map.removeLayer();
      }
      // map.removeLayer();
      if (res.data.length === 0 && posIndex == 0) {
        if (window.wsObjTimer) {
          msg.error('没有查到定位信息');
        }
        posIndex++;
      }
      map.position(res.data);
      // };
    }, positionTime);
  }

  function stop() {
    clearInterval(window.wsObjTimer);
    window.wsObjTimer = null;
    map.removeLayer();
    map.close();
    posIndex = 0;
  }
  function removeLayer() {
    map.removeLayer();
  }
  function setArea(points: []) {
    if (!points.length) return;
    map.loadArea(points);
  }
  function setHistoryLine(data) {
    map.setHistoryLine(data);
  }
  function removeHistoryLine(data) {
    map.removeHistoryLine(data);
  }
  return {
    position: {},
    area: {
      setArea,
    },
    history: {
      setHistoryLine,
      removeHistoryLine,
    },
    common: {
      loadMap,
      initPosition,
      stop,
      removeLayer,
    },
    map,
  };
};
